﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Threading;

namespace BluSteamServer.Model
{
    public class Network
    {
        #region Methods

        public static void Send(string username, string message)
        {
            byte[] bytes = Encoding.ASCII.GetBytes(message);

            lock (ConnectionManager.Instance.ValueLock)
            {
                Socket socket = ConnectionManager.Instance.GetSocket(username);

                if (socket != null)
                    socket.Send(bytes, 0, bytes.Length, SocketFlags.None);
            }
        }

        public static void Broadcast(string message)
        {
            lock (ConnectionManager.Instance.ValueLock)
            {
                // get reference to the connections dictionary
                Dictionary<string, Socket> clients = ConnectionManager.Instance.GetConnectionDictionary();

                // send message to all connected clients
                foreach (KeyValuePair<string, Socket> client in clients)
                {
                    byte[] bytes = Encoding.ASCII.GetBytes(message);
                    client.Value.Send(bytes, 0, bytes.Length, SocketFlags.None);
                    Thread.Sleep(1000);
                }
            }
        }

        // send multiple messages to one user - 1 from each connected client
        public static void SendMessageForEachUser(string message, string username)
        {
            lock (ConnectionManager.Instance.ValueLock)
            {
                // get reference to the connections dictionary
                Dictionary<string, Socket> clients = ConnectionManager.Instance.GetConnectionDictionary();
                Socket socket = ConnectionManager.Instance.GetSocket(username);

                // send message to all client except username
                foreach (KeyValuePair<string, Socket> client in clients)
                {
                    if (username == client.Key) continue;
                    string newMessage = message + client.Key;
                    byte[] bytes = Encoding.ASCII.GetBytes(newMessage);
                    socket.Send(bytes, 0, bytes.Length, SocketFlags.None);
                    Thread.Sleep(1000);
                }
            }
        }

        #endregion
    }
}
